package com.avic.rong.publishVideo.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.activity.mine.MyReleaseActivity;
import com.avic.rong.publishVideo.api.PublishVideoApi;
import com.avic.rong.userOrder.MyFile;
import com.avic.rong.userOrder.UploadFile;
import com.avic.rong.userOrder.api.UploadApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.SDCardUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.utils.UIUtil;
import com.avic.rong.utils.Utils;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.coorchice.library.utils.LogUtils;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.avic.rong.userOrder.MyFile.ITEM_TYPE_PIC_Btn;

public class PublishVideoActivity extends BaseActivity {


    @BindView(R.id.videoBtn)
    ImageView videoBtn;

    @BindView(R.id.tv_back)
    TextView tv_back;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;

    @BindView(R.id.videoplayer)
    JZVideoPlayerStandard videoplayer;
    @BindView(R.id.et_video_title)
    EditText etVideoTitle;
    @BindView(R.id.et_video_subtitle)
    EditText etVideoSubtitle;
    @BindView(R.id.video_publish_btn)
    TextView videoPublishBtn;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    @BindView(R.id.ll_video_select)
    LinearLayout ll_video_select;

    @BindView(R.id.tv_again_edit)
    TextView tv_again_edit;


    // 被选择要上传的文件列表
    private List<MyFile> selectedFileList;

    // 获取视频从存储
    public static final int VIDEO_FROM_STORE = 4;

    /**
     * 图片和视频的限制的总个数
     * 默认是9个
     */
    public static final int IMAGE_VIDEO_TOTAL_COUNT = 9;

    // 视频限制个数
    public static final int VIDEO_LIMIT_COUNT = 1;

    // 获取视频从相机
    public static final int VIDEO_FROM_CAMERA = 3;

    /**
     * 选择视频的类型
     */
    private int VIDEO_TYPE = 2;

    //视频编辑
    private String PATH = "path";

    private int PATH_REQUESTCODE = 100;

    //编辑后的视频
    private String EDIT_PATH = "edit_path";

    private OrientationUtils orientationUtils;

    private String videoUrl;

    private ImageView imageView;

    private MyFile myFile;

    //上传视频时长
    private long videoTime = 0;
    private Bitmap videoBitmap;
    //最终视频上传的路径
    private String video;

    private Boolean isEdit=false;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_publish_video;
    }

    @Override
    protected void initView() {
        tvTitle.setText("编辑视频信息");
        loading_layout.setStatus(LoadingLayout.SUCCESS);
        selectedFileList = new ArrayList<MyFile>();

    }


    @Override
    protected void addListener() {
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEdit){
                    DialogCustom.showDoubleDialog(PublishVideoActivity.this, "", "确定要放弃编辑这段视频吗？", "取消", "确定", new DialogCustom.CustomDialogDouble() {
                        @Override
                        public void rightButtonClicked() {
                            if (JZVideoPlayer.backPress()) {
                                return;
                            }
                            finish();
                        }

                        @Override
                        public void leftButtonClicked() {

                        }
                    });
                }else {
                    finish();
                }


            }
        });

        //选取视频
        ll_video_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
                RxPermissions permissions = new RxPermissions(PublishVideoActivity.this);
                // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        Log.e(TAG, "权限==" + aBoolean);

                        if (aBoolean) {
//                            showToast("选择视频");
                            /**
                             * 如果共选择的数量 > = 9 个 ,不能在选择视频
                             */


                            if (selectedFileList != null && selectedFileList.size() > 0) {
                                if (selectedFileList.size() >= IMAGE_VIDEO_TOTAL_COUNT) {
                                    ToastTools.showToast(PublishVideoActivity.this, "最多上传9个内容");
                                    return;
                                }
                            }

                            if (canAdd(UploadFile.TYPE_VIDEO, VIDEO_LIMIT_COUNT)) {
                                createVideoSelectDialog();
                            } else {
                                ToastTools.showToast(PublishVideoActivity.this, "视频最多支持" + VIDEO_LIMIT_COUNT + "个");
                            }
                        } else {
                            Toast.makeText(context, "权限被拒绝", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                        Toast.makeText(context, "请开启相关权限", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
            }
        });


        //发布视频
        videoPublishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharedPreferencesUtil.isLogin()){
                  /*  PublishTipDialog publishTipDialog = new PublishTipDialog(PublishVideoActivity.this,"审核通过后会发布在融融网平台,如有疑问请联系客服400-6006658");
                    publishTipDialog.setCallBackInterface(new PublishTipDialog.CallBackInterface() {
                        @Override
                        public void cannel() {


                        }
                    });
                    publishTipDialog.show();*/


                    String videoTitle = etVideoTitle.getText().toString().trim();
                    if (TextUtils.isEmpty(videoTitle)) {
                        ToastTools.showToast(PublishVideoActivity.this, "请填写视频标题");
                        return;
                    } else if (myFile == null) {
                        ToastTools.showToast(PublishVideoActivity.this, "请选择视频");
                        return;
                    }
                    //上传视频
                    doUploadVideo(myFile);
                } else {
                    startActivity(LoginPhoneActivity.getIntent(PublishVideoActivity.this,"PublishVideoActivity"));
                }

            }
        });

        //重新选取视频
        tv_again_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedFileList.clear();
                videoplayer.setVisibility(View.GONE);
                tv_again_edit.setVisibility(View.GONE);
                ll_video_select.setVisibility(View.VISIBLE);
            }
        });

        etVideoTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                    if (s.length()>0){
                        isEdit=true;
                    }
            }
        });
        etVideoSubtitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>0){
                    isEdit=true;
                }
            }
        });
    }

    /**
     * 上传
     *
     * @param files
     */
    private void doUploadVideo(File files) {


        if (files != null) {
            UploadApi uploadApi = new UploadApi(this, simpleOnNextListenerVideoUpload);

            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files);

            MultipartBody.Part part = MultipartBody.Part.createFormData("file", files.getName(), requestBody);
            uploadApi.setPart(part);
            uploadApi.setBaseUrl("https://nm.rongrong.cn/");
            HttpManager.getInstance().doHttpDeal(uploadApi);
//            loading_layout.setStatus(LoadingLayout.LOADING);
            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(uploadApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            showDialogTitle("正在发布...");
        }

    }

    //上传视频
    HttpOnNextListener simpleOnNextListenerVideoUpload = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(PublishVideoActivity.this, subjects.getMsg());
                return;
            }
            video = (String) subjects.getData();
            if (!TextUtils.isEmpty(video)) {

                Log.i("videUrl======", video);
                //上传封面图
                doUploadImage();


            }


        }


        @Override
        public void onError(final Throwable e) {
            dismissDialogTitle();
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    private void doUploadImage() {
        if (videoBitmap == null) return;
        File file = saveFile(videoBitmap);
        if (file != null) {
            UploadApi uploadApi = new UploadApi(this, simpleOnNextListenerVideoCoverUpload);
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);

            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
            uploadApi.setPart(part);
            uploadApi.setBaseUrl("https://nm.rongrong.cn/");
            HttpManager.getInstance().doHttpDeal(uploadApi);
//            loading_layout.setStatus(LoadingLayout.LOADING);
            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(uploadApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });

        }


    }

    private void submitPublishContent(String video, String videoCover) {
        if (SharedPreferencesUtil.isLogin()) {
            String videoTitle = etVideoTitle.getText().toString().trim();
            String subVideoTitle = etVideoSubtitle.getText().toString().trim();
            if (TextUtils.isEmpty(videoTitle)) {
                ToastTools.showToast(PublishVideoActivity.this, "请填写视频标题");
                return;
            } else if (TextUtils.isEmpty(video)) {
                ToastTools.showToast(PublishVideoActivity.this, "为获取到视频url");
                return;
            }
            Map<String, String> map = new HashMap<>();
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            map.put("title", videoTitle);
            map.put("intro", subVideoTitle);
            //5是 视频 4是app 图文
            map.put("typeFlg", 5 + "");
            //0:草稿 1:发布 3:审核中 4:拒绝 5:用户草稿
            map.put("status", 3 + "");
            if (TextUtils.isEmpty(video)) {
                return;
            }
            map.put("url", video);
            if (TextUtils.isEmpty(videoCover)) {
                return;
            }
            map.put("contImg", videoCover);
            if (videoTime > 0) {
                map.put("duraction", (videoTime/1000) + "");
            }

            PublishVideoApi publishVideoApi = new PublishVideoApi(PublishVideoActivity.this, simpleOnNextListenerUpdateContent);
            publishVideoApi.setCache(false);
            publishVideoApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(publishVideoApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(publishVideoApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });

        } else {
            startActivity(LoginPhoneActivity.getIntent(this,"PublishVideoActivity"));
        }
    }
    //上传视频封面图

    HttpOnNextListener simpleOnNextListenerVideoCoverUpload = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(PublishVideoActivity.this, subjects.getMsg());
                return;
            }
            String videoCover = (String) subjects.getData();
            if (!TextUtils.isEmpty(videoCover)) {
                //提交发布内容
                submitPublishContent(video, videoCover);
            }


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            dismissDialogTitle();
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };
    //发布内容监听
    HttpOnNextListener simpleOnNextListenerUpdateContent = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(PublishVideoActivity.this, subjects.getMsg());
                return;
            }
            ToastTools.showToast(PublishVideoActivity.this,"已提交审核，审核通过后发布");
            dismissDialogTitle();
            startActivity(MyReleaseActivity.queryIntentVideo(PublishVideoActivity.this,2));
            finish();
        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            dismissDialogTitle();
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    // 创建选择视频的dialog
    private void createVideoSelectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择视频来源");
//
        builder.setItems(new String[]{"拍摄视频", "选取视频", "取消"},
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                              /*  Intent intent = new Intent(
                                        MediaStore.ACTION_VIDEO_CAPTURE);
                                startActivityForResult(intent, VIDEO_FROM_CAMERA);*/
                                if (Build.VERSION.SDK_INT >= 23) {//6.0才用动态权限
                                    initPermission();
                                } else {
                                    //说明权限都已经通过，可以做你想做的事情去
                                    Intent intent = new Intent(PublishVideoActivity.this, RecordVideoActivity.class);
                                    startActivityForResult(intent, VIDEO_FROM_CAMERA);
                                }
                                /*if (ContextCompat.checkSelfPermission(PublishMyShowActivity.this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                                    ActivityCompat.requestPermissions(PublishMyShowActivity.this, new String[]{Manifest.permission.CAMERA}, 1000);
                                } else {
                                    Intent intent = new Intent(PublishMyShowActivity.this, RecordVideoActivity.class);
                                    startActivity(intent);
                                }*/

                                break;
                            case 1:
                                Intent intent2 = new Intent(
                                        Intent.ACTION_GET_CONTENT);
                                intent2.setType("video/*");
                                startActivityForResult(intent2, VIDEO_FROM_STORE);
                                break;
                            default:
                                break;
                        }
                    }
                });
        builder.create().show();
    }

    //申请三个权限，录音和文件读写、相机
    //1、首先声明一个数组permissions，将需要的权限都放在里面

    String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    //2、创建一个mPermissionList，逐个判断哪些权限未授予，未授予的权限存储到mPerrrmissionList中
    List<String> mPermissionList = new ArrayList<>();

    private final int mRequestCode = 100;//权限请求码

    //权限判断和申请
    private void initPermission() {

        mPermissionList.clear();//清空没有通过的权限

        //逐个判断你要的权限是否已经通过
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);//添加还未授予的权限
            }
        }

        //申请权限
        if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
            ActivityCompat.requestPermissions(this, permissions, mRequestCode);
        } else {
            //说明权限都已经通过，可以做你想做的事情去
            Intent intent = new Intent(PublishVideoActivity.this, RecordVideoActivity.class);
            startActivityForResult(intent, VIDEO_FROM_CAMERA);
        }
    }

    /**
     * 判断是否还能添加指定类型的文件
     *
     * @param fileType 文件类型
     * @param max      文件限制最大个数
     * @return 如果可以继续添加则返回true，否者返回false
     */
    private boolean canAdd(int fileType, int max) {
        int count = 0;
        for (int i = 0; i < selectedFileList.size(); i++) {
            MyFile myFile = selectedFileList.get(i);
            if (myFile.getFileType() == fileType) {
                count++;
            }
        }
        if (count >= max) {
            return false;
        }
        return true;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mRequestCode){
            Intent intent = new Intent(PublishVideoActivity.this, RecordVideoActivity.class);
            startActivityForResult(intent, VIDEO_FROM_CAMERA);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_OK) {
//            if (data != null && data.getData() != null) {
//                Uri uri = data.getData();
            if (requestCode == VIDEO_FROM_CAMERA) {
                // 视频
//                    String path = Utils.getVideoPathForUri(context, uri);
                String video_path = data.getStringExtra("video_path");
                LogUtils.i("========" + video_path);
                videoTime = UIUtil.getVideoDuration(video_path);
                MyFile myFile = new MyFile(video_path, UploadFile.TYPE_VIDEO);
                addSelectedFileToLayout(myFile, VIDEO_TYPE);
            } else if (requestCode == VIDEO_FROM_STORE) {
                if (data != null && data.getData() != null) {
                    Uri uri = data.getData();
                    String path = Utils.getVideoPathForUri(context, uri);
                    Log.e("================", "path=========" + path);
//                    Intent intent = new Intent(PublishMyShowActivity.this, EasyActivity.class);
//                    intent.putExtra(PATH,path);
//                    startActivityForResult(intent,);
                    long videoDuration = UIUtil.getVideoDuration(path);
                    videoTime = UIUtil.getVideoDuration(path);
                    //视频时长大于10秒需要编辑
                    if (videoDuration > 10000) {
                        //视频编辑
                        Intent intent = new Intent(PublishVideoActivity.this, EsayVideoEditActivity.class);
                        intent.putExtra(PATH, path);
                        startActivityForResult(intent, PATH_REQUESTCODE);
                    } else {
                        MyFile myFile = new MyFile(path, UploadFile.TYPE_VIDEO);
                        addSelectedFileToLayout(myFile, 0);
                    }

                }
            }
            //编辑压缩后的视频路径
            if (requestCode == PATH_REQUESTCODE) {
                String edit_path = data.getStringExtra(EDIT_PATH);
                videoTime = UIUtil.getVideoDuration(edit_path);
                MyFile myFile = new MyFile(edit_path, UploadFile.TYPE_VIDEO);
                addSelectedFileToLayout(myFile, 0);

            }

            /*else if (requestCode == AUDIO_FROM_STORE) {
                    String path = uri.getPath();
                    if (TextUtils.isEmpty(path) || path.lastIndexOf(".amr") == -1) {
                        showToast("无效文件,请选择.amr文件");
                        return;
                    }

                    MyFile myFile = new MyFile(path, UploadFile.TYPE_AUDIO);
                    addSelectedFileToLayout(myFile, VIDEO_TYPE);
                }*/
//            }


        }

    }

    // 把已选择的文件添加到布局显示出来
    private void addSelectedFileToLayout(MyFile file, int type) {
        if (file == null || !file.exists()) {
            ToastTools.showToast(PublishVideoActivity.this, "无效选取");
            return;
        }


        file.setItemType(MyFile.ITEM_TYPE_PIC_VIDEO);
        file.setSpanSize(MyFile.SPAN_SIZE_ONE);

        selectedFileList.add(file);


//        if (selectedFileList.size()>0&&selectedFileList.size()<9&&selectedFileList!=null){
//            iv_add_imge.setVisibility(View.VISIBLE);
//        }else {
//            iv_add_imge.setVisibility(View.GONE);
//        }


//        if (type==VIDEO_TYPE){
//            iv_add_imge.setVisibility(View.GONE);
//        }


        if (selectedFileList.size() >= 1) {

            ll_video_select.setVisibility(View.GONE);

            if (selectedFileList.get(0) != null) {

                videoplayer.setVisibility(View.VISIBLE);
                tv_again_edit.setVisibility(View.VISIBLE);
                myFile = selectedFileList.get(0);
                videoUrl = myFile.getPath();

                imageView = new ImageView(PublishVideoActivity.this);
                imageView.setImageResource(R.mipmap.ic_dai_fahuo_bg);

                videoplayer.setUp(videoUrl
                        , JZVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "");
//                videoBitmap = ThumbnailUtils.createVideoThumbnail(
//                        myFile.getAbsolutePath(),
//                        MediaStore.Images.Thumbnails.MICRO_KIND);

                // 获取最大关键帧
//                Bitmap bmp = ThumbnailUtils.createVideoThumbnail("/sdcard/0001.mp4", MediaStore.Images.Thumbnails.MINI_KIND);

// 获取第一个关键帧
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(myFile.getAbsolutePath());
                videoBitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

                videoplayer.thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                videoplayer.thumbImageView.setImageBitmap(videoBitmap);

                isEdit=true;
            }

        } else {

            ll_video_select.setVisibility(View.VISIBLE);
            videoplayer.setVisibility(View.GONE);
            tv_again_edit.setVisibility(View.GONE);

        }
//        MyFile myFileBt=new MyFile("",0);
//        selectedFileList.add(myFileBt);
        LogUtils.i("==========setNewData================");


    }

    private MyFile getMyFlieBtn() {
        MyFile myFile = new MyFile("", UploadFile.TYPE_IMAGE);
        myFile.setItemType(ITEM_TYPE_PIC_Btn);
        myFile.setSpanSize(MyFile.SPAN_SIZE_ONE);
        return myFile;
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }
    //将Bitmap类型的图片转化成file类型，便于上传到服务器
   /* public File saveFile(Bitmap bm) throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/videocover";
        File dirFile = new File(path);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;

    }*/

    public File saveFile(Bitmap bm) {
        try {
            String path = SDCardUtils.getSDCardPath() + "/revoeye/";
            File dirFile = new File(path);
            if (!dirFile.exists()) {
                dirFile.mkdir();
            }
            File myCaptureFile = new File(path + "videocover.jpg");
            BufferedOutputStream bos;
            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
            return myCaptureFile;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


}
